package controller;

import pojo.User;
import service.AddpowerService;
import service.UserService;
import service.impl.AddpowerServiceImpl;
import service.impl.UserServiceImpl;
import util.BeanUtils;
import util.TipsUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    /**
     * 用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String userLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        resp.setContentType("text/html;charset=utf-8");
        String usename = req.getParameter("usename");
        String password = req.getParameter("password");
        UserService userService = new UserServiceImpl();
        boolean login = userService.userLogin(usename, password);
        User userLogin = userService.findUserByUsername(usename);
//        UserDao userDao = new UserDaoImpl();
        if (!login) {
            req.setAttribute("fail", "用户名或密码错误");
//            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return "g_/login.jsp";
        } else {
            HttpSession session = req.getSession();
            session.setAttribute("usename", usename);
            session.setAttribute("userLogin", userLogin);
//            Cookie cookie=new Cookie("usename",usename);
//            Cookie cookie1=new Cookie("password",password);
//            cookie.setMaxAge(7*24*60*60);
//            cookie1.setMaxAge(7*24*60*60);
//            cookie.setPath("/");
//            cookie1.setPath("/");
//            resp.addCookie(cookie);
//            resp.addCookie(cookie1);

            //System.out.println("servlet="+userLogin);
//            req.getRequestDispatcher("/pageServlet?action=allNotesPage").forward(req, resp);
            return "g_/pageServlet?action=allNotesPage";
            //resp.sendRedirect( "/pageServlet?action=allNotesPage");
        }
    }


    /**
     * 用户注册
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
//        resp.setContentType("text/html;charset=utf-8");
//        String usename = req.getParameter("usename");
//        String password = req.getParameter("password");
//        String telephone = req.getParameter("telephone");
//        String age = req.getParameter("birthday");
//        String gender = req.getParameter("gender");
//        User user = new User();
        User user1 = new User();
        user1 = (User) BeanUtils.parameterEncapsulation(Class.forName("pojo.User"), req);
        /**
         * 检验
         */
        UserService userService = new UserServiceImpl();
        boolean check = userService.checkUserLogin(user1);
//        User user = new User();
//        boolean exit = false;
//        UserService userService = new UserServiceImpl();
//        User userLogin = userService.findUserByUsername(user1.getUsename());
//        if (userLogin == null) {
//            exit = true;
//        }
//        boolean checkUsename = user.setUsename(user1.getUsename());
//        boolean checkPassword = user.setPassword(user1.getPassword());
//        user.setGender(user1.getGender());
//        boolean checkTelephone = user.setTelephone(user1.getTelephone());
//        boolean checkAge = user.setAge(user1.getAge());
//        boolean check = false;
//        if (exit && checkUsename && checkPassword && checkTelephone && checkAge) check = true;
//        boolean flag = userService.userRegist(user);
        if (!check)
//            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return "g_/login.jsp";
        else {
//            resp.sendRedirect("/login.jsp");
            return "s_/login.jsp";
        }
    }

    /**
     * 查找用户笔记
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String findUserPageNote(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usename = req.getParameter("usename");
        String currentPage = req.getParameter("currentPage");
        String rows = req.getParameter("rows");
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = "5";
        }
        req.setAttribute("usename", usename);
        //req.getRequestDispatcher("/usernotes.jsp").forward(req, resp);
        return "g_/usernotes.jsp";
    }

    /**
     * 根据id查找用户信息回显
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        int uid = Integer.parseInt(req.getParameter("uid"));
        UserService userService = new UserServiceImpl();
        User userfind = new User();
        userfind = userService.findUser(uid);
        req.setAttribute("userfind", userfind);
        //req.getRequestDispatcher("/updateUser.jsp").forward(req, resp);
        return "g_updateUser.jsp";
    }

    /**
     * 修改用户信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String updateUserInformation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        req.setCharacterEncoding("utf-8");
//        Integer uid = Integer.parseInt(req.getParameter("uid"));
//        //System.out.println(uid);
//        String usename = req.getParameter("usename");
//        //System.out.println(usename);
//        String password = req.getParameter("password");
//        //System.out.println(password);
//        String telephone = req.getParameter("telephone");
//        //System.out.println(telephone);
//        String gender = req.getParameter("gender");
//        //System.out.println(gender);
//        String age = req.getParameter("age");
//        //System.out.println(age);
        User user1 = new User();
        user1 = (User) BeanUtils.parameterEncapsulation(Class.forName("pojo.User"), req);
        System.out.println(user1);
        //User newuser = new User();
//        newuser.setAge(user1.getAge());
//        newuser.setTelephone(user1.getTelephone());
//        newuser.setGender(user1.getGender());
//        newuser.setUsename(user1.getUsename());
//        newuser.setPassword(user1.getPassword());
//        newuser.setUid(user1.getUid());
        //System.out.println(newuser);
        UserService userService = new UserServiceImpl();
        //boolean flag = userService.updateUserInformation(newuser);
        boolean flag = userService.updateUserInformation(user1);
        System.out.println(flag);
        //System.out.println(flag);
        if (flag)
//            resp.sendRedirect( "/userInformation.jsp");
            return "s_/userInformation.jsp";
        else
//            resp.sendRedirect("/userInformation.jsp");
            return "s_/error.jsp";
    }

    /**
     * 检验注册的用户名是否已经存在
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void userRegistByUsename(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, ClassNotFoundException {
        resp.setContentType("text/html;charset=utf-8");
        String usename = req.getParameter("usename");
        resp.setContentType("text/html;charset=utf-8");
        Map<String, Object> map = new HashMap<String, Object>();
        UserService userService = new UserServiceImpl();
        User userLogin = userService.findUserByUsername(usename);
        boolean login = false;
        if (userLogin.getUsename().equals(usename)) login = true;
        if (login) {
            //失败
            map.put("login", true);
            map.put("msg", "用户名已存在，请更换一个");
        } else {
            //成功
            map.put("login", false);
            map.put("msg", "用户名可用");
        }
        HttpSession session = req.getSession();
        session.setAttribute("userLogin", userLogin);
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.writeValue(resp.getWriter(), map);
        TipsUtil.tips(req, resp, map);
    }

    /**
     * 取消禁止权限
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String addUserAddpower(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int mid = Integer.parseInt(req.getParameter("mid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        AddpowerService addpowerService = new AddpowerServiceImpl();
        boolean flag = addpowerService.addUserAddpower(mid, uid);
        req.setAttribute("mid", mid);
        if (flag) {
//            req.getRequestDispatcher("/pageServlet?action=areaUsersPage").forward(req, resp);
            return "g_/pageServlet?action=areaUsersPage";
        } else
            return "s_/error.jsp";
    }

    /**
     * 添加禁止权限
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String deleteUserAddpower(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int mid = Integer.parseInt(req.getParameter("mid"));
        int uid = Integer.parseInt(req.getParameter("uid"));
        AddpowerService addpowerService = new AddpowerServiceImpl();
        boolean flag = addpowerService.deleteUserAddpower(mid, uid);
        req.setAttribute("mid", mid);
        if (flag) {
//            req.getRequestDispatcher("/pageServlet?action=areaUsersPage").forward(req, resp);
            return "g_/pageServlet?action=areaUsersPage";
        } else return "s_/error.jsp";
        //        String type=req.getParameter("type");
//        String usename=req.getParameter("usename");
//        UserDaoImpl implementUser=new UserDaoImpl();
//        User user=new User();
//        req.getParameter("type");
//        //try {
//            user=implementUser.getuser(usename);
//            implementUser.updatepower(user);
//            req.getRequestDispatcher("/findAreaUserPage").forward(req,resp);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }
}
